package com.example.jimuyutabletcontrol.activity;

import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.DistanceUtil;
import com.example.jimuyutabletcontrol.R;
import com.example.jimuyutabletcontrol.utils.Constants;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class AnalysingGPSDHActivity extends AppCompatActivity implements View.OnClickListener {

    private MapView mapView;
    private BaiduMap baiduMap;
    private LocationClient mLocationClient;
    private AnalysingGPSDHActivity.MyLocationListener myLocationListener;
    private File file;

    /*
    private Button loadStartGps;
    private Button loadTaskGps;
    private Button loadCalculateGps;
    private Button loadRealGps;
    private Button loadMappingData;
    private Button showTwoPointDistance;
    private Button deleteMappingPoint;
    private Button deleteAllPoint;
    */

    private ArrayList<Double> curLongtitude;
    private ArrayList<Double> curLatitude;
    private ArrayList<Double> missionLongtitude;
    private ArrayList<Double> missionLatitude;
    private ArrayList<Double> realLongtitude;
    private ArrayList<Double> realLatitude;
    private List<LatLng> distancePoints;
    private ArrayList<Overlay> distanceOverlay;
    private Overlay polyline;
    private Overlay mText;

    private List<Overlay> mMarkerListOverlayMission;
    private List<LatLng> mLatLngListMission;
    private List<Overlay> mPolylineListOverlayMission;
    private int checkpolymission;

    private int[] marker = {
            R.drawable.taskmap_icon_marka, R.drawable.taskmap_icon_markb,
            R.drawable.taskmap_icon_markc, R.drawable.taskmap_icon_markd,
            R.drawable.taskmap_icon_marke, R.drawable.taskmap_icon_markf,
            R.drawable.taskmap_icon_markg, R.drawable.taskmap_icon_markh,
            R.drawable.taskmap_icon_marki, R.drawable.taskmap_icon_markj
    };

    private Point[] pentagonVertices;
    private FloatingActionButton fabTools;
    private Button[] buttonsTools;
    private int startPositionX;
    private int startPositionY;
    private int toolsWhichAnimation;
    private int[] enterDelay = {0, 40, 80, 120, 160, 200, 240};
    private int[] exitDelay = {0, 40, 80, 120, 160, 200, 240};
    private Boolean isFabToolsClicked = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.analysinggpsdhinterface_activity);

        mapView = findViewById(R.id.bmapViewanalysegpsdh);
        baiduMap = mapView.getMap();
        /*
        loadStartGps = findViewById(R.id.loadstartgps);
        loadTaskGps = findViewById(R.id.loadtaskgps);
        loadCalculateGps = findViewById(R.id.loadcalculategps);
        loadRealGps = findViewById(R.id.loadrealgps);
        loadMappingData = findViewById(R.id.loadmappingdata);
        showTwoPointDistance = findViewById(R.id.showtwopointdistance);
        deleteMappingPoint = findViewById(R.id.deletemappingpoint);
        deleteAllPoint = findViewById(R.id.deleteallpoint);
        */

        initSourceContainer();
        setBaseMapConf();
        setLocationRegister();
        setClickListener();
        prepareFloatButton();
        setGpsInformation();
    }


    private void setGpsInformation() {
        buttonsTools[0].setEnabled(false);
        buttonsTools[0].setBackgroundResource(R.drawable.disable_circular_background);
        buttonsTools[1].setEnabled(false);
        buttonsTools[1].setBackgroundResource(R.drawable.disable_circular_background);
        buttonsTools[2].setEnabled(false);
        buttonsTools[2].setBackgroundResource(R.drawable.disable_circular_background);
        buttonsTools[3].setEnabled(false);
        buttonsTools[3].setBackgroundResource(R.drawable.disable_circular_background);
        buttonsTools[5].setEnabled(false);
        buttonsTools[5].setBackgroundResource(R.drawable.disable_circular_background);
        buttonsTools[6].setEnabled(false);
        buttonsTools[6].setBackgroundResource(R.drawable.disable_circular_background);
        /*
        loadStartGps.setEnabled(false);
        loadTaskGps.setEnabled(false);
        loadCalculateGps.setEnabled(false);
        loadRealGps.setEnabled(false);
        deleteMappingPoint.setEnabled(false);
        deleteAllPoint.setEnabled(false);
        */

        String fileName = getIntent().getStringExtra("fileName");

        file = new File(Constants.FILE_PATH + Constants.DH + fileName);

        if (file.exists()) {
            curLongtitude = new ArrayList<>();
            curLatitude = new ArrayList<>();
            missionLongtitude = new ArrayList<>();
            missionLatitude = new ArrayList<>();
            realLongtitude = new ArrayList<>();
            realLatitude = new ArrayList<>();

            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line = br.readLine();
                line = br.readLine();
                while (line != null) {
                    String[] contents = line.split(" ");
                    curLongtitude.add(Double.parseDouble(contents[9]));
                    curLatitude.add(Double.parseDouble(contents[10]));
                    missionLongtitude.add(Double.parseDouble(contents[11]));
                    missionLatitude.add(Double.parseDouble(contents[12]));
                    realLongtitude.add(Double.parseDouble(contents[13]));
                    realLatitude.add(Double.parseDouble(contents[14]));
                    line = br.readLine();
                }
                br.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        buttonsTools[0].setEnabled(true);
        buttonsTools[0].setBackgroundResource(R.drawable.circular_background);
        buttonsTools[1].setEnabled(true);
        buttonsTools[1].setBackgroundResource(R.drawable.circular_background);
        buttonsTools[2].setEnabled(true);
        buttonsTools[2].setBackgroundResource(R.drawable.circular_background);
        buttonsTools[3].setEnabled(true);
        buttonsTools[3].setBackgroundResource(R.drawable.circular_background);
        buttonsTools[5].setEnabled(true);
        buttonsTools[5].setBackgroundResource(R.drawable.circular_background);
        buttonsTools[6].setEnabled(true);
        buttonsTools[6].setBackgroundResource(R.drawable.circular_background);

        /*
        loadStartGps.setEnabled(true);
        loadTaskGps.setEnabled(true);
        loadCalculateGps.setEnabled(true);
        loadRealGps.setEnabled(true);
        deleteMappingPoint.setEnabled(true);
        deleteAllPoint.setEnabled(true);
        */
    }

    private void setClickListener() {
        BaiduMap.OnMapLongClickListener longClickListener = new BaiduMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                if (distancePoints != null && distancePoints.size() != 2) {
                    distancePoints.add(latLng);
                    OverlayOptions option = new MarkerOptions().position(latLng)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.taskmap_icon_distance));
                    distanceOverlay.add(baiduMap.addOverlay(option));
                }
                if (distancePoints.size() == 2 && polyline == null) {
                    OverlayOptions mOverlayOptions = new PolylineOptions()
                            .width(5)
                            .color(Color.BLACK)
                            .points(distancePoints);
                    polyline = baiduMap.addOverlay(mOverlayOptions);
                    OverlayOptions mTextOptions = new TextOptions()
                            .text("" + DistanceUtil.getDistance(distancePoints.get(0), distancePoints.get(1))) //文字内容
                            .bgColor(0xAAFFFF00) //背景色
                            .fontSize(24) //字号
                            .fontColor(0xFFFF00FF) //文字颜色
                            .position(latLng);
                    mText = baiduMap.addOverlay(mTextOptions);
                    //TODO
                    //showTwoPointDistance.setText(String.valueOf(DistanceUtil.getDistance(distancePoints.get(0), distancePoints.get(1))));
                }
            }
        };
        baiduMap.setOnMapLongClickListener(longClickListener);
    }

    private void initSourceContainer() {
        mMarkerListOverlayMission = new ArrayList<>();
        mLatLngListMission = new ArrayList<>();
        mPolylineListOverlayMission = new ArrayList<>();
        distancePoints = new ArrayList<>();
        distanceOverlay = new ArrayList<>();
        checkpolymission = 0;
    }

    private void addMissionPointToMap(LatLng latLng) {
        if (checkpolymission <= 9) {
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(marker[checkpolymission]);
            OverlayOptions option = new MarkerOptions()
                    .position(latLng)
                    .icon(bitmap);
            checkpolymission++;
            if (checkpolymission > 1) {
                LatLng point1 = mLatLngListMission.get(checkpolymission - 2);
                LatLng point2 = latLng;
                List<LatLng> points = new ArrayList<LatLng>();
                points.add(point1);
                points.add(point2);
                OverlayOptions mOverlayOptions = new PolylineOptions()
                        .width(10)
                        .color(Color.MAGENTA)
                        .points(points);
                Overlay mPolyline = baiduMap.addOverlay(mOverlayOptions);
                mPolylineListOverlayMission.add(mPolyline);
            }

            Overlay overlay = baiduMap.addOverlay(option);
            mMarkerListOverlayMission.add(overlay);
            mLatLngListMission.add(latLng);
        } else {
            toastMsg("标点超过限制数10个");
        }
    }

    private void setBaseMapConf() {
        baiduMap.clear();
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(4.0f);
        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    private void setLocationRegister() {
        mLocationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
        myLocationListener = new AnalysingGPSDHActivity.MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
    }


    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.zoom(16.0f);
            baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(status);//动画的方式到中间
            mLocationClient.stop();
            baiduMap.setMyLocationEnabled(false);
        }
    }

    private void toastMsg(final String msg) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private LatLng gpsToBaidu(LatLng point) {
        CoordinateConverter converter = new CoordinateConverter();
        converter.from(CoordinateConverter.CoordType.GPS);
        converter.coord(point);
        LatLng changePoint = converter.convert();

        return changePoint;
    }


    @Override
    public void onClick(View view) {
        boolean isToolsSubClicked = false;

        switch (view.getId()) {
            case R.id.fabanalysinggpsdhtool:
                isToolsSubClicked = true;
                isFabToolsClicked = true;
                if (toolsWhichAnimation == 0) {
                    /**
                     * Getting the center point of floating action button
                     *  to set start point of buttons
                     */
                    startPositionX = 2600;
                    startPositionY = 0;

                    for (Button button : buttonsTools) {
                        button.setX(startPositionX);
                        button.setY(startPositionY);
                        button.setVisibility(View.VISIBLE);
                    }
                    for (int i = 0; i < buttonsTools.length; i++) {
                        playEnterAnimation(buttonsTools[i], i);
                    }
                    toolsWhichAnimation = 1;
                } else {
                    for (int i = 0; i < buttonsTools.length; i++) {
                        playExitAnimation(buttonsTools[i], i);
                    }
                    toolsWhichAnimation = 0;
                    isFabToolsClicked = false;
                }
                break;
        }
        if (isFabToolsClicked && !isToolsSubClicked) {
            switch ((int) view.getTag()) {
                case 0:
                    if (curLongtitude.size() != 0 && curLatitude.size() != 0) {
                        MapStatus.Builder builder = new MapStatus.Builder();
                        builder.zoom(19.0f);
                        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                        LatLng ll = gpsToBaidu(new LatLng(curLatitude.get(0), curLongtitude.get(0)));
                        MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
                        baiduMap.animateMapStatus(status);//动画的方式到中间
                        baiduMap.setMyLocationEnabled(true);
                        BitmapDescriptor bitmap = BitmapDescriptorFactory
                                .fromResource(R.drawable.taskmap_icon_start);
                        OverlayOptions option = new MarkerOptions()
                                .position(gpsToBaidu(new LatLng(curLatitude.get(0), curLongtitude.get(0))))
                                .icon(bitmap);
                        baiduMap.addOverlay(option);
                    } else {
                        toastMsg("所选文件内没有数据记录!!!");
                    }
                    break;
                case 1:
                    if (!file.exists()) {
                        toastMsg("你所选的文件已经找不到，请再次确认!!!");
                    } else if (curLongtitude.size() == 0) {
                        toastMsg("所选文件内没有数据记录!!!");
                    } else {
                        buttonsTools[1].setEnabled(false);
                        buttonsTools[1].setBackgroundResource(R.drawable.disable_circular_background);
                        //loadTaskGps.setEnabled(false);
                        double newLantitudeMission = 0.0;
                        double newLongtitudeMission = 0.0;
                        int missionLength = missionLatitude.size();
                        for (int i = 0; i < missionLength; i++) {
                            double tmpLatitude = missionLatitude.get(i);
                            double tmpLongtitude = missionLongtitude.get(i);
                            if (newLongtitudeMission != tmpLongtitude || newLantitudeMission != tmpLatitude) {
                                addMissionPointToMap(
                                        gpsToBaidu(new LatLng(missionLatitude.get(i), missionLongtitude.get(i))));
                                newLongtitudeMission = tmpLongtitude;
                                newLantitudeMission = tmpLatitude;
                            }
                        }
                    }
                    break;
                case 2:
                    if (!file.exists()) {
                        toastMsg("你所选的文件已经找不到，请再次确认!!!");
                    } else if (curLongtitude.size() == 0) {
                        toastMsg("所选文件内没有数据记录!!!");
                    } else {
                        buttonsTools[2].setEnabled(false);
                        buttonsTools[2].setBackgroundResource(R.drawable.disable_circular_background);
                        //loadCalculateGps.setEnabled(false);

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                List<LatLng> points = new ArrayList<>();
                                int length = curLatitude.size();
                                for (int i = 0; i < length; i++) {
                                    points.add(gpsToBaidu(new LatLng(curLatitude.get(i), curLongtitude.get(i))));
                                }

                                OverlayOptions mOverlayOptions = new PolylineOptions()
                                        .width(10)
                                        .color(Color.CYAN)
                                        .points(points);
                                baiduMap.addOverlay(mOverlayOptions);
                            }
                        }).start();
                    }
                    break;
                case 3:
                    if (!file.exists()) {
                        toastMsg("你所选的文件已经找不到，请再次确认!!!");
                    } else if (realLongtitude.size() == 0) {
                        toastMsg("所选文件内没有数据记录!!!");
                    } else {
                        buttonsTools[3].setEnabled(false);
                        buttonsTools[3].setBackgroundResource(R.drawable.disable_circular_background);
                        new Thread(() -> {
                            List<LatLng> points = new ArrayList<>();
                            int length = realLatitude.size();
                            for (int i = 0; i < length; i++) {
                                points.add(gpsToBaidu(new LatLng(realLatitude.get(i), realLongtitude.get(i))));
                            }
                            OverlayOptions mOverlayOptions = new PolylineOptions()
                                    .width(10)
                                    .color(Color.YELLOW)
                                    .points(points);
                            baiduMap.addOverlay(mOverlayOptions);
                        }).start();
                    }
                    break;
                case 4:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                List<OverlayOptions> ooCircles = new ArrayList<>();
                                File file = new File(Constants.FILE_PATH + Constants.MAPPINGFOLDER + Constants.MAPPINGFILE);
                                if (!file.exists()) {
                                    toastMsg("无测绘数据文件");
                                    return;
                                }
                                BufferedReader br = new BufferedReader(new FileReader(file));
                                String line = br.readLine();
                                System.out.println("line: " + line);
                                while (line != null) {
                                    String[] content = line.split(" ");
                                    ooCircles.add(new CircleOptions().center(
                                            gpsToBaidu(new LatLng(Double.valueOf(content[1]), Double.valueOf(content[0]))))
                                            .fillColor(0xffff0000).radius(2));
                                    line = br.readLine();
                                }
                                br.close();
                                if (ooCircles.size() != 0) {
                                    AnalysingGPSDHActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            buttonsTools[4].setEnabled(false);
                                            buttonsTools[4].setBackgroundResource(R.drawable.disable_circular_background);

                                            //loadMappingData.setEnabled(false);
                                        }
                                    });
                                    baiduMap.addOverlays(ooCircles);
                                } else {
                                    toastMsg("文件内无测绘数据");
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();
                    break;
                case 5:
                    if (distancePoints.size() != 0) {
                        distancePoints.clear();
                        distancePoints = new ArrayList<>();
                        for (Overlay overlay : distanceOverlay) {
                            overlay.remove();
                        }
                        distanceOverlay.clear();
                        distanceOverlay = new ArrayList<>();
                    }

                    if (polyline != null) {
                        polyline.remove();
                        polyline = null;
                    }
                    if (mText != null) {
                        mText.remove();
                    }
                    break;
                case 6:
                    baiduMap.clear();

                    buttonsTools[1].setEnabled(true);
                    buttonsTools[1].setBackgroundResource(R.drawable.circular_background);
                    buttonsTools[2].setEnabled(true);
                    buttonsTools[2].setBackgroundResource(R.drawable.circular_background);
                    buttonsTools[3].setEnabled(true);
                    buttonsTools[3].setBackgroundResource(R.drawable.circular_background);
                    buttonsTools[4].setEnabled(true);
                    buttonsTools[4].setBackgroundResource(R.drawable.circular_background);
                    /*
                    loadTaskGps.setEnabled(true);
                    loadCalculateGps.setEnabled(true);
                    loadRealGps.setEnabled(true);
                    loadMappingData.setEnabled(true);
                    */

                    checkpolymission = 0;
                    mPolylineListOverlayMission.clear();
                    mPolylineListOverlayMission = new ArrayList<>();
                    mLatLngListMission.clear();
                    mLatLngListMission = new ArrayList<>();
                    mMarkerListOverlayMission.clear();
                    mMarkerListOverlayMission = new ArrayList<>();

                    distancePoints.clear();
                    distancePoints = new ArrayList<>();
                    if (polyline != null) {
                        polyline.remove();
                        polyline = null;
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(myLocationListener);
            mLocationClient.stop();
            mLocationClient = null;
        }
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
    }

    private void prepareFloatButton() {
        startPositionX = 0;
        startPositionY = 0;
        toolsWhichAnimation = 0;
        fabTools = (FloatingActionButton) findViewById(R.id.fabanalysinggpsdhtool);

        fabTools.setOnClickListener(this);

        pentagonVertices = new Point[10];
        pentagonVertices[0] = new Point(10, 100);
        pentagonVertices[1] = new Point(10, 280);
        pentagonVertices[2] = new Point(10, 460);
        pentagonVertices[3] = new Point(10, 640);
        pentagonVertices[4] = new Point(10, 820);
        pentagonVertices[5] = new Point(10, 1000);
        pentagonVertices[6] = new Point(10, 1180);

        String[] contentTools = {"出发位置", "任务数据", "推算数据", "实际数据", "测绘数据", "清除测距", "清除图标"};

        buttonsTools = calculatePentagonVertices(7, contentTools);
    }

    private Button[] calculatePentagonVertices(int number, String[] content) {

        Button[] buttons = new Button[number];

        for (int i = 0; i < buttons.length; i++) {
            //Adding button at (0,0) coordinates and setting their visibility to zero
            buttons[i] = new Button(AnalysingGPSDHActivity.this);
            buttons[i].setLayoutParams(new RelativeLayout.LayoutParams(100, 100));
            buttons[i].setX(0);
            buttons[i].setY(0);
            buttons[i].setTag(i);
            buttons[i].setOnClickListener(this);
            buttons[i].setVisibility(View.INVISIBLE);
            buttons[i].setBackgroundResource(R.drawable.circular_background);
            buttons[i].setTextColor(Color.DKGRAY);
            buttons[i].setText(content[i]);
            buttons[i].setTextSize(14);
            /**
             * Adding those buttons in acitvities layout
             */
            ((LinearLayout) findViewById(R.id.analysinggpsdh_main)).addView(buttons[i]);
        }

        return buttons;
    }

    private void playEnterAnimation(final Button button, int position) {

        /**
         * Animator that animates buttons x and y position simultaneously with size
         */
        AnimatorSet buttonAnimator = new AnimatorSet();

        /**
         * ValueAnimator to update x position of a button
         */
        ValueAnimator buttonAnimatorX = ValueAnimator.ofFloat(startPositionX,
                pentagonVertices[position].x);
        buttonAnimatorX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.setX((float) animation.getAnimatedValue());
                button.requestLayout();
            }
        });
        buttonAnimatorX.setDuration(300);

        /**
         * ValueAnimator to update y position of a button
         */
        ValueAnimator buttonAnimatorY = ValueAnimator.ofFloat(startPositionY,
                pentagonVertices[position].y);
        buttonAnimatorY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.setY((float) animation.getAnimatedValue());
                button.requestLayout();
            }
        });
        buttonAnimatorY.setDuration(300);

        /**
         * This will increase the size of button
         */
        ValueAnimator buttonSizeAnimator = ValueAnimator.ofInt(6, 170);
        buttonSizeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.getLayoutParams().width = (int) animation.getAnimatedValue();
                button.getLayoutParams().height = (int) animation.getAnimatedValue();
                button.requestLayout();
            }
        });
        buttonSizeAnimator.setDuration(300);

        /**
         * Add both x and y position update animation in
         *  animator set
         */
        buttonAnimator.play(buttonAnimatorX).with(buttonAnimatorY).with(buttonSizeAnimator);
        buttonAnimator.setStartDelay(enterDelay[position]);
        buttonAnimator.start();
    }

    private void playExitAnimation(final Button button, int position) {

        /**
         * Animator that animates buttons x and y position simultaneously with size
         */
        AnimatorSet buttonAnimator = new AnimatorSet();

        /**
         * ValueAnimator to update x position of a button
         */
        ValueAnimator buttonAnimatorX = ValueAnimator.ofFloat(pentagonVertices[position].x,
                startPositionX);
        buttonAnimatorX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.setX((float) animation.getAnimatedValue());
                button.requestLayout();
            }
        });
        buttonAnimatorX.setDuration(300);

        /**
         * ValueAnimator to update y position of a button
         */
        ValueAnimator buttonAnimatorY = ValueAnimator.ofFloat(pentagonVertices[position].y,
                startPositionY);
        buttonAnimatorY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.setY((float) animation.getAnimatedValue());
                button.requestLayout();
            }
        });
        buttonAnimatorY.setDuration(300);

        /**
         * This will decrease the size of button
         */
        ValueAnimator buttonSizeAnimator = ValueAnimator.ofInt(170, 6);
        buttonSizeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.getLayoutParams().width = (int) animation.getAnimatedValue();
                button.getLayoutParams().height = (int) animation.getAnimatedValue();
                button.requestLayout();
            }
        });
        buttonSizeAnimator.setDuration(300);

        /**
         * Add both x and y position update animation in
         *  animator set
         */
        buttonAnimator.play(buttonAnimatorX).with(buttonAnimatorY).with(buttonSizeAnimator);
        buttonAnimator.setStartDelay(exitDelay[position]);
        buttonAnimator.start();
    }
}
